{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Genre propagation\n",
    "\n",
    "Genres get assigned to MARC records quite late in the game (it's not really common till the 1990s). So in restricting our dataset to the earliest available example of a book, we lose a lot of genre info.\n",
    "\n",
    "This notebook aims to restore it."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "import numpy as np\n",
    "import csv"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "volmap = dict()\n",
    "with open('allgroups.tsv', encoding = 'utf-8') as f:\n",
    "    for line in f:\n",
    "        vols = line.strip().split('\\t')\n",
    "        volset = set(vols)\n",
    "        for v in vols:\n",
    "            if v not in volmap:\n",
    "                volmap[v] = set(volset)\n",
    "            else:\n",
    "                for v1 in vols:\n",
    "                    volmap[v].add(v1)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "work = pd.read_csv('../workmeta.tsv', sep = '\\t', low_memory = False, index_col = 'docid')\n",
    "manifest = pd.read_csv('../manifestationmeta.tsv', sep = '\\t', low_memory = False, index_col = 'docid')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loaded\n",
      "0.132679875775\n"
     ]
    }
   ],
   "source": [
    "genres = dict()\n",
    "subjects = dict()\n",
    "\n",
    "increased = []\n",
    "\n",
    "with open('../manifestationmeta.tsv', encoding = 'utf-8') as f:\n",
    "    reader = csv.DictReader(f, delimiter = '\\t')\n",
    "    for row in reader:\n",
    "        docid = row['docid']\n",
    "        s = row['subjects'].replace(';', '|')\n",
    "        g = row['genres'].replace(';', '|')\n",
    "        subjects[docid] = set(s.split('|'))\n",
    "        genres[docid] = set(g.split('|'))\n",
    "\n",
    "print('loaded')\n",
    "\n",
    "allrows = []\n",
    "\n",
    "with open('../workmeta.tsv', encoding = 'utf-8') as f:\n",
    "    reader = csv.DictReader(f, delimiter = '\\t')\n",
    "    fieldnames = reader.fieldnames\n",
    "    for row in reader:\n",
    "        docid = row['docid']\n",
    "        s = row['subjects'].replace(';', '|')\n",
    "        g = row['genres'].replace(';', '|')\n",
    "        s = set(s.split('|'))\n",
    "        g = set(g.split('|'))\n",
    "        glen = len(g)\n",
    "        if docid in volmap:\n",
    "            for d in volmap[docid]:\n",
    "                s = s.union(subjects[d])\n",
    "                g = g.union(genres[d])\n",
    "        \n",
    "        increase = len(g) - glen\n",
    "        increased.append(increase)\n",
    "        \n",
    "        g = [x.strip() for x in g if len(x.strip()) > 1]\n",
    "        s = [x.strip() for x in s if len(x.strip()) > 1]\n",
    "        \n",
    "        row['genres'] = '|'.join(g)\n",
    "        row['subjects'] = '|'.join(s)\n",
    "        allrows.append(row)\n",
    "\n",
    "fieldnames.pop(fieldnames.index('shorttitle'))\n",
    "fieldnames.append('shorttitle')\n",
    "# make title last\n",
    "\n",
    "with open('../enrichedworkmeta.tsv', mode = 'w', encoding = 'utf-8') as f:\n",
    "    writer = csv.DictWriter(f, fieldnames = fieldnames, delimiter = '\\t')\n",
    "    writer.writeheader()\n",
    "    for row in allrows:\n",
    "        writer.writerow(row)\n",
    "        \n",
    "            \n",
    "increased = np.array(increased)\n",
    "print(np.mean(increased))\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.13267987577549822"
      ]
     },
     "execution_count": 12,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "sum(increased) / len(increased)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(work.columns.tolist())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
